<?php
namespace app\api\model;

use app\admin\event\SystemLog;
use app\admin\model\Admin;
use think\db\Query;
use think\exception\DbException;
use think\Model;
use think\Db;

class PurchaseModel extends Base
{
    protected static function init()
    {
        self::observe(SystemLog::class);
    }

    protected $table ='jxc_purchase';

    // 定义全局的查询范围
    protected function base($query)
    {
        $c = Admin::find(\app\http\GetUid::getUId());
        // 门店负责人可查看自己门店的所有信息
        if ($c->level == 2) {
            $maker = Admin::where('store', $c->store)->where('level', 3)->column('id');
        } elseif ($c->level == 1) {
            $maker = Admin::column('id');
        } else {
            $maker = $c->id;
        }
        $query->whereIn('uid', $maker);
    }
    /**
     * @param $status
     * @param $startime
     * @param $endtime
     * @param $supplier
     * @param $warehouse
     * @param $number
     * @return array|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getPurchaseList($data)
    {
        $where =[];
        if (!empty($data['status'])) {
            $where[] =['status','=',$data['status']];
        }
        if (!empty($data['start_time']) && !empty($data['end_time'])) {
            $where[] = ['create_time','between', [$data['start_time'], $data['end_time']]];
        }
        if (!empty($data['supplier'])) {
            $where[] =['supplier','=',$data['supplier']];
        }
        if (!empty($data['warehouse'])) {
            $where[] =['warehouse','=',$data['warehouse']];
        }
        if (!empty($data['number'])) {
            $where[] = ['number','like', "%" . $data['number'] . "%"];
        }
        $list =$this->getPage('purchase','id,status,number,create_time,supplier,warehouse,uid,set_account,total,payment,des',$where,'id desc',$data['page'],$data['size']);
        $list =$list->toArray();
        foreach ($list['data'] as $k=>$v){
            $list['data'][$k]['create_time'] =date('Y-m-d',$v['create_time']);
            $list['data'][$k]['supplier'] =$this->getValue('supplier',['id'=>$v['supplier']],'name');
            $list['data'][$k]['warehouse'] =$this->getValue('warehouse',['id'=>$v['warehouse']],'name');
            $list['data'][$k]['uid'] =$this->getValue('admin',['id'=>$v['uid']],'name');
            $list['data'][$k]['set_account'] =$this->getValue('set_account',['id'=>$v['set_account']],'name');
            switch ($v['status']){
               case 1:
                   $list['data'][$k]['status1'] = "待入库";
                   break;
                case 2:
                   $list['data'][$k]['status1'] = "部分入库";
                   break;
               case 3:
                    $list['data'][$k]['status1'] = "撤销";
                   break;
                case 4:
                    $list['data'][$k]['status1'] = "已采购";
                    break;
               default:
                    $list['data'][$k]['status1'] = "草稿";
            }
        }
        return $list;
    }

    /*public function getCacheColor($id)
    {
        $current =$this->getOne('product','commodity_id,color',['id'=>$id]);
        $arr =$this->getselectList('product','id,color',['commodity_id'=>$current['commodity_id']]);
        $color =[];
        $str1 =[];
        foreach ($arr as $k=>$v){
            if($v['color'] !=$current['color']){
                if(!in_array($v['color'],$str1)){
                    $str1[] = $v['color'];
                    $color[] = ['id'=>$v['id'],
                        'color'=>$this->getValue('color3',['id'=>$v['color']],'name'),
                        'color_id' =>$v['color']
                    ];
                }
            }
        }
        return $color;
    }

    public function getCacheSize($id)
    {
        $current =$this->getOne('product','commodity_id,size',['id'=>$id]);
        $arr =$this->getselectList('product','id,size',['commodity_id'=>$current['commodity_id']]);
        $str =[];
        $str1 =[];
        foreach ($arr as $k=>$v){
            if($v['size'] !=$current['size']){
                if(!in_array($v['size'],$str1)){
                    $str1[] = $v['size'];
                    $str[] = ['id'=>$v['id'],
                        'size'=>$this->getValue('color3',['id'=>$v['size']],'name'),
                        'size_id' =>$v['size']
                    ];
                }
            }
        }
        return $str;
    }

    public function getEditProduct($data , $spec)
    {
        foreach($spec['option'] as $k=>$v){
            if($data['id'] == $v['id']){
                $num =$v['num'];
                $spec['option'][$k]['num'] = 0;
            }
            if($data['color'] == $v['color'] && $data['size'] == $v['size']){
                $spec['option'][$k]['num'] =$v['num'] + $num;
            }
        }
        return $spec;
    }*/

    public function getGoodsStock($id)
    {
        $list =$this->getselectList('product','id,color,size',['commodity_id'=>$id]);
        foreach($list as $k=>$v){
            $list[$k]['num'] =$this->getValue('product_stock',['product_id'=>$v['id']],'stock');
            $list[$k]['size']=$this->getValue('color3',['id'=>$v['size']],'name');
            $list[$k]['color']=$this->getValue('color3',['id'=>$v['color']],'name');
        }
        return $list;
    }

    /**
     * @param $data
     * @return int|string
     */
    public function getPurchaseAdd($data)
    {
        $arr = $this::create($data);
        if($data['status'] ==1){
            foreach ($data['goods'] as $k => $v) {
                $relation['product_id'] = $v['product_id'];
                $relation['put_number'] = $v['put_number'];
                $relation['pid'] = $arr->id;
                $relation['price'] = $v['price'];
                $relation['discount'] = $v['discount'];
                $relation['discount_price'] = $v['discount_price'];
                $relation['money'] = $v['money'];
                $relation['discount_money'] = $v['discount_money'];
                $this->getAdd('purchaserelation', $relation);
                $stockInfo =$this->getOne('product_stock','*',['product_id'=>$v['product_id'],'warehouse'=>$data['warehouse']]);
                if(empty($stockInfo)){
                    $commodity_id =$this->getValue('product',['id'=>$v['product_id']],'commodity_id');
                    $rel =[
                        'commodity_id' => $commodity_id,
                        'product_id' => $v['product_id'],
                        'warehouse' => $data['warehouse'],
                        'put_in' => $v['put_number']
                    ];
                    $this->getAdd('product_stock', $rel);
                }else{
                    $this->getSetInc('product_stock',['product_id'=>$v['product_id'],'warehouse'=>$data['warehouse']],'put_in',$v['put_number']);
                }
            }
            $stock['status'] =1;
            $stock['number'] = $data['number'];
            $stock['create_time'] =$data['create_time'];
            $stock['supplier'] =$data['supplier'];
            $stock['warehouse'] =$data['warehouse'];
            $stock['maker'] =$data['uid'];
            $stock['type'] =1;//单据类型 1采购单 2生产入库单 3调拨单
            $stock['des'] =$data['des'];
            $stock['relation_id'] =$arr->id;
            $this->getAdd('instock',$stock);
        }else{
            foreach ($data['goods'] as $k => $v) {
                $relation['product_id'] = $v['product_id'];
                $relation['put_number'] = $v['put_number'];
                $relation['pid'] = $arr->id;
                $relation['price'] = $v['price'];
                $relation['discount'] = $v['discount'];
                $relation['discount_price'] = $v['discount_price'];
                $relation['money'] = $v['money'];
                $relation['discount_money'] = $v['discount_money'];
                $this->getAdd('purchaserelation', $relation);
                $stockInfo =$this->getOne('product_stock','*',['product_id'=>$v['product_id'],'warehouse'=>$data['warehouse']]);
                if(empty($stockInfo)){
                    $commodity_id =$this->getValue('product',['id'=>$v['product_id']],'commodity_id');
                    $rel =[
                        'commodity_id' => $commodity_id,
                        'product_id' => $v['product_id'],
                        'warehouse' => $data['warehouse'],
                        'stock' => 0
                        ];
                    $this->getAdd('product_stock', $rel);
                }
            }
        }
        return $arr;
    }

    /**
     * @param $id
     * @return array|\PDOStatement|string|Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getPurchaseInfo($id)
    {
        $list = $this->getOne('purchase','*',['id'=>$id]);
        $list['goods'] = $this->getselectList('purchaserelation','*',['pid'=>$list['id']]);
        foreach($list['goods'] as $k=>$v){
            $dan =$this->getOne('product','commodity_id,color,size',['id'=>$v['product_id']]);
            $goods =$this->getOne('commodity','name,item,goods_code,unit',['id'=>$dan['commodity_id']]);
            $list['goods'][$k]['commodity_id'] =$dan['commodity_id'];
            $list['goods'][$k]['name'] =$goods['name'];
            $list['goods'][$k]['item'] =$goods['item'];
            $list['goods'][$k]['goods_code'] =$goods['goods_code'];
            $list['goods'][$k]['color'] =$this->getValue('color3',['id'=>$dan['color']],'name');
            $list['goods'][$k]['size'] =$this->getValue('color3',['id'=>$dan['size']],'name');
            $list['goods'][$k]['unit'] =$this->getValue('color1',['id'=>$goods['unit']],'name');
        }
        $list['user_name'] = $this->getValue('user',['id'=>$list['uid']],'name');
        $list['warehouse_name'] =$this->getValue('warehouse',['id'=>$list['warehouse']],'name');
        $list['supplier_name'] =$this->getValue('supplier',['id'=>$list['supplier']],'name');
        $list['supplier_phone'] =$this->getValue('supplier',['id'=>$list['supplier']],'phone');
        $list['set_account_name'] =$this->getValue('set_account',['id'=>$list['set_account']],'name');
        $list['type_name'] =$this->getValue('account_type',['id'=>$list['type']],'name');
        $list['create_time'] = date('Y-m-d', $list['create_time']);
        $list['images'] =json_decode($list['images'],true);
        $list['type1'] = '采购单';
        switch ($list['status']){
            case 1:
                $list['status_name'] = "待入库";
                break;
            case 2:
                $list['status_name'] = "部分入库";
                break;
            case 3:
                $list['status_name'] = "撤销";
                break;
            case 4:
                $list['status_name'] = "已采购";
                break;
            default:
                $list['status_name'] = "草稿";
        }
        return $list;
    }

    /**
     * @param $id
     * @return array|int|\PDOStatement|string|Model|null
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function getPurchaseDel($id)
    {
        try{
            $list =$this->getOne('purchase','*',['id'=>$id]);
            if(in_array($list['status'],[2,3,4])){
                throw new \Exception('单据已入库,无法删除');
            }else{
                if($list['status'] ==1){
                    Db::name('instock')->where(['relation_id'=>$id,'type'=>1])->delete();
                }
                Db::name('purchaserelation')->whereIn('pid',$id)->delete();
                return $this->getDel('purchase',$id);
            }
        } catch (DbException $e) {
            return $e->getMessage();
        }
    }

    /**
     * @param $id
     * @return array|int|\PDOStatement|string|Model|null
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function getPurchaseRevoke($id)
    {
        try{
            $list =$this->getOne('purchase','*',['id'=>$id]);
            if(in_array($list['status'],[2,4])){
                throw new \Exception('单据已入库,无法撤销');
            }else{
                if($list['status'] ==1){
                    $this->getSetField('instock',array('relation_id'=>$id,'type'=>1),['status'=>4]);
                }
                return $this->getSetField('purchase',['id'=>$id],['status'=>3]);
            }
        } catch (DbException $e) {
            return $e->getMessage();
        }
    }

    public function getPurchaseDraft($id,$data)
    {
        $list = $this->getEdit('purchase',['id'=>$id],$data);
        Db::name('purchaserelation')->whereIn('pid',$id)->delete();
        foreach ($data['goods'] as $k=>$v){
            $v['pid'] =$id;
            $this->getAdd('purchaserelation',$v);
            $stockInfo =$this->getOne('product_stock','*',['product_id'=>$v['product_id'],'warehouse'=>$data['warehouse']]);
            if(empty($stockInfo)){
                $rel =[
                    'commodity_id' => $v['commodity_id'],
                    'product_id' => $v['product_id'],
                    'warehouse' => $data['warehouse'],
                    'stock' => 0
                ];
                $this->getAdd('product_stock', $rel);
            }
        }
        return $list;
    }

    public function getPutStock($id,$data)
    {
        $this->getEdit('purchase',['id'=>$id],$data);
        Db::name('purchaserelation')->whereIn('pid',$id)->delete();
        foreach ($data['goods'] as $k=>$v){
            $v['pid'] =$id;
            $this->getAdd('purchaserelation',$v);
            $stockInfo =$this->getOne('product_stock','*',['product_id'=>$v['product_id'],'warehouse'=>$data['warehouse']]);
            if(empty($stockInfo)){
                $rel =[
                    'commodity_id' => $v['commodity_id'],
                    'product_id' => $v['product_id'],
                    'warehouse' => $data['warehouse'],
                    'put_in' => $v['put_number']
                ];
                $this->getAdd('product_stock', $rel);
            }else{
                $this->getSetInc('product_stock',['product_id'=>$v['product_id'],'warehouse'=>$data['warehouse']],'put_in',$v['put_number']);
            }
        }
        $list =$this->getOne('purchase','*',['id'=>$id]);
        $stock['status'] =1;
        $stock['number'] =$list['number'];
        $stock['create_time'] =$list['create_time'];
        $stock['supplier'] =$list['supplier'];
        $stock['warehouse'] =$list['warehouse'];
        $stock['maker'] =$list['uid'];
        $stock['type'] =1;//单据类型 1采购单 2生产入库单 3调拨单 4销售退货单  5配货退货单
        $stock['des'] =$list['des'];
        $stock['relation_id'] =$id;
        return $this->getAdd('instock',$stock);
    }

    /**
     * 全部入库
     * @param $id
     * @return string|\think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getAllDepot($id)
    {
        $list = $this->getOne('purchase','*',['id'=>$id]);
        $list['goods'] = $this->getselectList('purchaserelation','*',['pid'=>$list['id']]);
        foreach ($list['goods'] as $k => $v) {
            $this->getSetField('purchaserelation',['id'=>$v['id']],['number'=>$v['put_number']]);
            $this->getSetInc('product_stock',['product_id'=>$v['product_id'],'warehouse'=>$list['warehouse']],'stock',$v['put_number']);
            $this->getSetDec('product_stock',['product_id'=>$v['product_id'],'warehouse'=>$list['warehouse']],'put_in',$v['put_number']);
            $stock =$this->getValue('product_stock',['product_id'=>$v['product_id'],'warehouse'=>$list['warehouse']],'stock');
            $flow =[
                'goods_id' =>$v['product_id'],
                'create_time' =>time(),
                'warehouse' =>$list['warehouse'],
                'type' =>'采购单',
                'number' =>$list['number'],
                'add_num' =>$v['put_number'],
                'sur_num' =>$stock + $v['put_number']
            ];
            $this->getAdd('flowing_water',$flow);
        }
        $payment =[
            'customer_id' => $list['supplier'],
            'customer_type' => 'supplier',
            'maker' => $list['uid'],
            'set_account' => $list['set_account'],
            'account_type_id' => $list['type'],
            'out_amount' => $list['payment'],
            'des' => $list['des'],
            'create_time' => time(),
            'images' => $list['images'],
            'business_type' => '采购单',
            'business_number' => $list['number'],
            'business_time' => $list['create_time'],
        ];
        $this->getAdd('set_account_flow', $payment);
        $small = [
            'customer_id' => $list['supplier'],
            'customer_type' => 'supplier',
            'maker' => $list['uid'],
            'set_account' => $list['set_account'],
            'account_type_id' => 15,
            'out_amount' => $list['small'],
            'des' => $list['des'],
            'create_time' => time(),
            'images' => $list['images'],
            'business_type' => '采购单',
            'business_number' => $list['number'],
            'business_time' => $list['create_time'],
        ];
        $this->getAdd('set_account_flow', $small);
        $feiyong = [
            'customer_id' => $list['supplier'],
            'customer_type' => 'supplier',
            'maker' => $list['uid'],
            'set_account' => $list['set_account'],
            'account_type_id' => 15,
            'out_amount' => $list['money'],
            'des' => $list['des'],
            'create_time' => time(),
            'images' => $list['images'],
            'business_type' => '采购单',
            'business_number' => $list['number'],
            'business_time' => $list['create_time'],
        ];
        $this->getAdd('set_account_flow', $feiyong);
        $this->getSetField('instock',array('relation_id'=>$list['id'],'type'=>1),['status'=>2]);
        return $this->getSetField('purchase',['id'=>$list['id']],['status'=>4]);
    }


    /**
     * 采购退货单
     * @param $status
     * @param $startime
     * @param $endtime
     * @param $supplier
     * @param $number
     * @return array|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getReturnList($data)
    {
        $where = [];
        if (!empty($data['status'])) {
            $where[] =['status','=',$data['status']];
        }
        if (!empty($data['start_time']) && !empty($data['end_time'])) {
            $where[] = ['create_time','between', [$data['start_time'], $data['end_time']]];
        }
        if (!empty($data['supplier'])) {
            $where[] =['supplier','=',$data['supplier']];
        }
        if (!empty($data['number'])) {
            $where[] = ['number','like', "%" . $data['number'] . "%"];
        }
        $list =$this->getPage('purchasereturn','id,status,number,create_time,supplier,warehouse,uid,set_account,payment,des',$where,'id desc',$data['page'],$data['size']);
        $list =$list->toArray();
        foreach ($list['data'] as $k=>$v){
            $list['data'][$k]['create_time'] =date('Y-m-d',$v['create_time']);
            $list['data'][$k]['supplier'] =$this->getValue('supplier',['id'=>$v['supplier']],'name');
            $list['data'][$k]['warehouse'] =$this->getValue('warehouse',['id'=>$v['warehouse']],'name');
            $list['data'][$k]['uid'] =$this->getValue('admin',['id'=>$v['uid']],'name');
            $list['data'][$k]['set_account'] =$this->getValue('set_account',['id'=>$v['set_account']],'name');
            switch ($v['status']){
                case 1:
                    $list['data'][$k]['status1'] = "已退货";
                    $list['data'][$k]['status2'] =8;
                    break;
                case 2:
                    $list['data'][$k]['status1'] = "已撤销";
                    $list['data'][$k]['status2'] =6;
                    break;
                default:
                    $list['data'][$k]['status1'] = "草稿";
                    $list['data'][$k]['status2'] =7;
            }
        }
        return $list;
    }

    /**
     * 采购退货 新增
     * @param $data
     * @return int|string
     */
    public function getReturnAdd($data)
    {
        $arr1 = $this->getAdd('purchasereturn',$data);
        if($data['status'] ==1){
            $stock['status'] =3;
            $stock['number'] =$data['number'];
            $stock['create_time'] =$data['create_time'];
            $stock['warehouse'] =$data['warehouse'];
            $stock['maker'] =$data['uid'];
            $stock['type'] =4;//单据类型  4采购退货单
            $stock['des'] =$data['des'];
            $stock['relation_id'] =$arr1;
            $this->getAdd('outstock',$stock);
            foreach ($data['goods'] as $k => $v) {
                $arr['product_id'] = $v['product_id'];
                $arr['put_number'] = $v['put_number'];
                $arr['price'] = $v['price'];
                $arr['number'] =$arr['put_number'];
                $arr['pid'] =$arr1;
                $arr['discount'] = $v['discount'];
                $arr['discount_price'] = $v['discount_price'];
                $arr['money'] = $v['money'];
                $arr['discount_money'] = $v['discount_money'];
                $this->getAdd('purchasereturnrelation',$arr);
                $stockInfo =$this->getOne('product_stock','*',['product_id'=>$v['product_id'],'warehouse'=>$data['warehouse']]);
                if(empty($stockInfo)){
                    $rel =[
                        'commodity_id' => $v['commodity_id'],
                        'product_id' => $v['product_id'],
                        'warehouse' => $data['warehouse'],
                        'stock' => '-'.$v['put_number']
                    ];
                    $this->getAdd('product_stock', $rel);
                }
                $this->getSetDec('product_stock',['product_id'=>$v['product_id'],'warehouse'=>$data['warehouse']],'stock',$v['put_number']);
                $flow =[
                    'goods_id' =>$v['product_id'],
                    'create_time' =>time(),
                    'warehouse' =>$data['warehouse'],
                    'type' =>'采购退货单',
                    'number' =>$data['number'],
                    'add_num' =>'-'.$v['put_number'],
                    'sur_num' =>(isset($stockInfo['stock']) ? $stockInfo['stock'] : 0) - $v['put_number']
                ];
                $this->getAdd('flowing_water',$flow);
            }
            $payment =[
                'customer_id' => $data['supplier'],
                'customer_type' => 'supplier',
                'maker' => $data['uid'],
                'set_account' => $data['set_account'],
                'out_amount' => $data['payment'],
                'des' => $data['des'],
                'create_time' => time(),
                'business_type' => '采购退货单',
                'business_number' => $data['number'],
                'business_time' => $data['create_time'],
            ];
            $this->getAdd('set_account_flow', $payment);
        }else{
            foreach ($data['goods'] as $k => $v) {
                $arr['product_id'] = $v['product_id'];
                $arr['put_number'] = $v['put_number'];
                $arr['price'] = $v['price'];
                $arr['number'] =0;
                $arr['pid'] =$arr1;
                $arr['discount'] = $v['discount'];
                $arr['discount_price'] = $v['discount_price'];
                $arr['money'] = $v['money'];
                $arr['discount_money'] = $v['discount_money'];
                $this->getAdd('purchasereturnrelation',$arr);
                $stockInfo =$this->getOne('product_stock','*',['product_id'=>$v['product_id'],'warehouse'=>$data['warehouse']]);
                if(empty($stockInfo)){
                    $rel =[
                        'commodity_id' => $v['commodity_id'],
                        'product_id' => $v['product_id'],
                        'warehouse' => $data['warehouse'],
                        'stock' => 0
                    ];
                    $this->getAdd('product_stock', $rel);
                }
            }
        }
        return $arr1;
    }

    public function getReturnDraft($id,$data)
    {
        $list = $this->getEdit('purchasereturn',['id'=>$id],$data);
        Db::name('purchasereturnrelation')->whereIn('pid',$id)->delete();
        foreach ($data['goods'] as $k=>$v){
            $rel['product_id'] =$v['product_id'];
            $rel['put_number'] =$v['put_number'];
            $rel['pid'] =$id;
            $rel['price'] =$v['price'];
            $rel['discount'] =$v['discount'];
            $rel['discount_price'] =$v['discount_price'];
            $rel['money'] =$v['money'];
            $rel['discount_money'] =$v['discount_money'];
            $rel['discount'] =$v['discount'];
            $this->getAdd('purchasereturnrelation',$rel);
            $stockInfo =$this->getOne('product_stock','*',['product_id'=>$v['product_id'],'warehouse'=>$data['warehouse']]);
            if(empty($stockInfo)){
                $commodity_id =$this->getValue('product',['id'=>$v['product_id']],'commodity_id');
                $rel2 =[
                    'commodity_id' => $commodity_id,
                    'product_id' => $v['product_id'],
                    'warehouse' => $data['warehouse'],
                    'stock' => 0
                ];
                $this->getAdd('product_stock', $rel2);
            }
        }
        return $list;
    }

    public function getPurchaseReturn($id,$data)
    {
        $arr =$this->getEdit('purchasereturn',['id'=>$id],$data);
        Db::name('purchasereturnrelation')->whereIn('pid',$id)->delete();
        foreach ($data['goods'] as $k=>$v){
            $rel['product_id'] =$v['product_id'];
            $rel['put_number'] =$v['put_number'];
            $rel['price'] =$v['price'];
            $rel['pid'] =$id;
            $rel['discount'] =$v['discount'];
            $rel['discount_price'] =$v['discount_price'];
            $rel['money'] =$v['money'];
            $rel['discount_money'] =$v['discount_money'];
            $rel['discount'] =$v['discount'];
            $this->getAdd('purchasereturnrelation',$rel);
            $stockInfo =$this->getOne('product_stock','*',['product_id'=>$v['product_id'],'warehouse'=>$data['warehouse']]);
            if(empty($stockInfo)){
                $commodity_id =$this->getValue('product',['id'=>$v['product_id']],'commodity_id');
                $rel2 =[
                    'commodity_id' => $commodity_id,
                    'product_id' => $v['product_id'],
                    'warehouse' => $data['warehouse'],
                    'stock' => '-'.$v['put_number']
                ];
                $this->getAdd('product_stock', $rel2);
            }else{
                $this->getSetDec('product_stock',['product_id'=>$v['product_id'],'warehouse'=>$data['warehouse']],'stock',$v['put_number']);
            }
        }
        $list =$this->getOne('purchasereturn','*',['id'=>$id]);
        $stock['status'] =3;
        $stock['number'] =$list['number'];
        $stock['create_time'] =$data['create_time'];
        $stock['supplier'] =$data['supplier'];
        $stock['warehouse'] =$data['warehouse'];
        $stock['maker'] =$data['uid'];
        $stock['type'] =4;//单据类型 1销售单 2配货单 3调拨单  4采购退货单
        $stock['des'] =$data['des'];
        $stock['relation_id'] =$id;
        $this->getAdd('outstock',$stock);
        $list['goods'] = $this->getselectList('purchasereturnrelation','*',['pid'=>$list['id']]);
        foreach($list['goods'] as $k=>$v){
            $this->getSetDec('product_stock', ['product_id' => $v['product_id'],'warehouse'=>$data['warehouse']], 'stock', $v['put_number']);
            $stock =$this->getValue('product_stock',['product_id'=>$v['product_id'],'warehouse'=>$data['warehouse']],'stock');
            $flow =[
                'goods_id' =>$v['product_id'],
                'create_time' =>time(),
                'warehouse' =>$data['warehouse'],
                'type' =>'采购退货单',
                'number' =>$list['number'],
                'add_num' =>'-'.$v['put_number'],
                'sur_num' =>$stock - $v['put_number']
            ];
            $this->getAdd('flowing_water',$flow);
        }
        $payment =[
            'customer_id' => $data['supplier'],
            'customer_type' => 'supplier',
            'maker' => $data['uid'],
            'set_account' => $data['set_account'],
            'out_amount' => $data['payment'],
            'des' => $data['des'],
            'create_time' => time(),
            'business_type' => '采购退货单',
            'business_number' => $list['number'],
            'business_time' => $data['create_time'],
        ];
        $this->getAdd('set_account_flow', $payment);
        return $arr;
    }

    /**
     * 采购退货 详情
     * @param $id
     * @return array|false|\PDOStatement|string|Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getReturnDetail($id)
    {
        $list = $this->getOne('purchasereturn','*',['id'=>$id]);
        $list['goods'] =$this->getselectList('purchasereturnrelation','*',['pid'=>$list['id']]);
        foreach($list['goods'] as $k=>$v){
            $dan =$this->getOne('product','commodity_id,color,size',['id'=>$v['product_id']]);
            $goods =$this->getOne('commodity','name,item,goods_code,unit',['id'=>$dan['commodity_id']]);
            $list['goods'][$k]['commodity_id'] =$dan['commodity_id'];
            $list['goods'][$k]['name'] =$goods['name'];
            $list['goods'][$k]['item'] =$goods['item'];
            $list['goods'][$k]['goods_code'] =$goods['goods_code'];
            $list['goods'][$k]['color'] =$this->getValue('color3',['id'=>$dan['color']],'name');
            $list['goods'][$k]['size'] =$this->getValue('color3',['id'=>$dan['size']],'name');
            $list['goods'][$k]['unit'] =$this->getValue('color1',['id'=>$goods['unit']],'name');
        }
        $list['warehouse_name'] =$this->getValue('warehouse',['id'=>$list['warehouse']],'name');
        $list['supplier_name'] =$this->getValue('supplier',['id'=>$list['supplier']],'name');
        $list['maker_name'] =$this->getValue('admin',['id'=>$list['uid']],'name');
        $list['supplier_phone'] =$this->getValue('supplier',['id'=>$list['supplier']],'phone');
        $list['set_account_name'] =$this->getValue('set_account',['id'=>$list['set_account']],'name');
        $list['create_time'] = date('Y-m-d', $list['create_time']);
        $list['warehouse'] = (int)$list['warehouse'];
        $list['supplier'] = (int)$list['supplier'];
        $list['type'] = '采购退货单';
        switch ($list['status']){
            case 1:
                $list['status1'] = "已退货";
                break;
            case 2:
                $list['status1'] = "已撤销";
                break;
            default:
                $list['status1'] = "草稿";
        }
        return $list;
    }

    /*public function getReturnDepot($id,$option)
    {
        $list = $this->getOne('purchasereturn','*',['id'=>$id]);
        $list['goods'] = $this->getselectList('purchasereturnrelation','*',['pid'=>$list['id']]);
        foreach ($list['goods'] as $k => $v) {
            $goods =$this->getValue('product',['id'=>$v['product_id']],'commodity_id');
            $this->getSetDec('product_stock',['product_id'=>$v['product_id']],'stock',$v['put_number']);
            $this->getSetField('purchasereturnrelation',['id'=>$v['id']],['number'=>$v['put_number']]);
            $this->getSetDec('warehouse_goods',['warehouse_id'=>$list['warehouse'],'goods_id'=>$goods],'stock',$v['put_number']);
            $stock =$this->getValue('warehouse_goods',['goods_id'=>$goods,'warehouse_id'=>$list['warehouse']],'stock');
            $flow =[
                'goods_id' =>$v['product_id'],
                'create_time' =>time(),
                'warehouse' =>$list['warehouse'],
                'type' =>'采购退货单',
                'number' =>$list['number'],
                'add_num' =>'-'.$v['put_number'],
                'sur_num' =>$stock - $v['put_number']
            ];
            $this->getAdd('flowing_water',$flow);
        }
        $this->getSetField('purchasereturn',['id'=>$list['id']],['status'=>1]);
        $this->getSetField('outstock',['relation_id'=>$id,'type'=>4],['status'=>3]);
        return 1;
    }*/

    /**
     * 采购退货 撤销
     * @param $id
     * @return array|false|int|\PDOStatement|string|Model
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function getReturnRevoke($id)
    {
        $list = $this->getOne('purchasereturn','*',['id'=>$id]);
        if(in_array($list['status'],[1,2])){
            return 1;
        }else{
            $this->getSetField('purchasereturn',['id'=>$id],['status'=>2]);
            $this->getSetField('outstock',array('relation_id'=>$id,'type'=>4),['status'=>4]);
            return 2;
        }
    }

    /**
     * 采购退货 删除
     * @param $id
     * @return array|false|int|\PDOStatement|string|Model
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function getReturnDel($id)
    {
        $list = $this->getOne('purchasereturn','*',['id'=>$id]);
        if(in_array($list['status'],[1,2])){
             return 1;
        }else{
            $this->getDel('purchasereturn',$id);
            Db::name('purchasereturnrelation')->whereIn('pid',$id)->delete();
            return 2;
        }
    }

    public function getTodayNum()
    {
        $start_time =date("Y-m-d H:i:s", mktime(0, 0, 0, date('m'), date('d'), date('Y')));
        $end_time = date("Y-m-d H:i:s", mktime(0, 0, 0, date('m'), date('d')+1, date('Y'))-1);
        $start_time =strtotime($start_time);
        $end_time =strtotime($end_time);
        //$where =[];
        $where[] =['create_time','between',[$start_time,$end_time]];
        $where[] =['status','=',4];
        $list['purchase'] =$this->getselectList('purchase','id,payment',$where);
        $purchase_id =[];
        $purchase_money =[];
        foreach($list['purchase'] as $k=>$v){
            $purchase_id[] =$v['id'];
            $purchase_money[] =$v['payment'];
        }
        $list['sale'] =$this->getselectList('sale','id,payment',$where);
        $sale_id =[];
        $sale_money =[];
        foreach($list['sale'] as $k=>$v){
            $sale_id[] =$v['id'];
            $sale_money[] =$v['payment'];
        }
        $data =[
            'purchase' => [
               'num' =>count($purchase_id),
                'money' =>array_sum($purchase_money)
            ],
            'sale' => [
                'num' =>count($sale_id),
                'money' =>array_sum($sale_money)
            ]
        ];
        return $data;
    }
}
